<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-form
            :inline="true"
            :model="queryForm"
            class="demo-form-inline"
            style="float: left"
            size="medium"
          >
            <el-form-item label="监测时间(年-月)：">
              <el-date-picker
                v-model="queryForm.yearMonth"
                type="month"
                placeholder="选择月"
                style="width: 160px"
                :default-value="currentDate"
                @change="onDateChange"
                :clearable="false"
              />
            </el-form-item>
            <el-form-item label="断面名称：">
              <el-input v-model="queryForm.keyword" placeholder="断面名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="success" @click="confirmSubmit">一键提交</el-button>
            </el-form-item>
          </el-form>
          <div
            style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            "
          >

          </div>
        </div>
        <div class="center">
          <el-table
            :data="paginatedData"
            border
            style="width: 100%"
            size="medium"
            :max-height="tableheight"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40" />
            <el-table-column label="序号" type="index" width="60px" />

            <el-table-column
              prop="dmmc"
              label="断面名称"
              show-overflow-tooltip
            />
            <el-table-column
              prop="liuyu"
              label="所在流域"
              show-overflow-tooltip
            />

            <el-table-column
              prop="xzqhname"
              label="行政区划"
              show-overflow-tooltip
            />
            <el-table-column
              prop="szmb"
              label="水质目标"
              show-overflow-tooltip
            />
            <el-table-column
              prop="szlb"
              label="水质类别"
              show-overflow-tooltip
            />
            <el-table-column
              prop="dmlaiyuan"
              label="断面类型"
              show-overflow-tooltip
            />

            <el-table-column prop="shenhezt" label="数据状态">
              <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row.shenhezt)" size="small">{{
                  getStatusText(scope.row.shenhezt)
                }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              prop="action"
              label="操作"
              width="170"
              align="center"
            >
              <template slot-scope="scope">
                <!-- 根据状态显示不同的按钮 -->
                <span v-if="scope.row.shenhezt === '00'">
                  <el-button
                    :type="scope.row.btnstate !== '1' ? 'primary' : 'info'"
                    size="mini"
                    @click="handleEntry(scope.row)"
                  >
                    录入
                  </el-button>
                </span>
                <span  v-else-if="['01', '04'].includes(scope.row.shenhezt)">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleEdit(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteItem(scope.row.dmszjcid)"
                  >
                    删除
                  </el-button>
                </span>
                <span v-else>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleView(scope.row)"
                  >
                    查看
                  </el-button>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="bottom">
        <el-pagination
          :current-page="currentPage"
          background
          layout="total, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          hide-on-single-page
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
    <el-dialog
    title="查看信息"
    :visible.sync="dialogVisible"
    :modal-append-to-body="false"
    top="10vh"
    width="760px">
    <el-descriptions style="margin-top: -30px;" :column="3" :labelStyle="{width: '135px'}" :contentStyle="{minWidth: '90px'}" size="medium" border>
      <el-descriptions-item label="断面名称" :span="2">{{ dmData.length > 0 ? dmData[0].dmmc : '' }}</el-descriptions-item>
      <el-descriptions-item label="水质类别">{{ dmData.length > 0 ? dmData[0].szlbname : '' }}</el-descriptions-item>
      <el-descriptions-item label="行政区划">{{ dmData.length > 0 ? dmData[0].xzqhname : '' }}</el-descriptions-item>
      <el-descriptions-item label="监测时间">{{ dmData.length > 0 ? dmData[0].liuyu : '' }}</el-descriptions-item>
      <el-descriptions-item label="水质目标">{{ dmData.length > 0 ? dmData[0].szmb : '' }}</el-descriptions-item>
      <el-descriptions-item label="所在流域">{{ dmData.length > 0 ? dmData[0].liuyu : '' }}</el-descriptions-item>
      <el-descriptions-item label="断面类型">{{ dmData.length > 0 ? dmData[0].dmlaiyuan : '' }}</el-descriptions-item>
      <template v-for="item in jcjgArray">
        <el-descriptions-item :label="item.label" :key="item.value">{{ dmData.length > 0 ? dmData[0][item.value] : '' }}</el-descriptions-item>
      </template>
      <el-descriptions-item label="监测报告" :span="3">
        <div v-for="(item, index) in dmData.length > 0 ? dmData[0].filelist : []" :key="item.name">
          <el-link :href="item.url" target="_blank" :underline="false">{{index + 1 + '、' + item.name}}</el-link>
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui'
import config, { shenhezt } from '@/config/config.js'
export default {
  name: "DataEntry",
  data() {
    return {
      tableheight: 300,
      value2: "",
      filteredData: [], // 根据查询条件过滤后的数据
      queryForm: {
        keyword: "", // 查询关键字
        yearMonth: "", // 年月信息
      },
      tableData: [], // 样地数据
      paginatedData: [], // 当前页的数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数

      isButtonDisabled: false, // 初始化按钮可点击状态
      buttonText: "录入全部数据", // 初始按钮文本
      // selection: [], // 用于存储用户选择的项目
      dialogVisible: false,
      errorMessages: [],
      jcjgArray: [],
      dmData: [],
      selectedIds: [],
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
    currentDate() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      return `${year}-${month < 10 ? "0" + month : month}`;
    },
  },
  created() {
    const height = window.innerHeight - 200;
    this.tableheight = height;
    this.jcjgArray = config.jcjgArray;
    // this.fetchData();
    // this.getData();
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
    this.getUser();
  },
  methods: {
    onDateChange(date) {
      if (!date) return; // 如果日期为空，则不发送请求
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      this.queryForm.yearMonth = `${year}-${month < 10 ? "0" + month : month}`;
      this.getUser(); // 调用获取数据的方法
    },
    // handleSelectionChange(val) {
    //   this.selection = val;
    // },
  
    getUser() {
      this.$api
        .getUser()
        .then((response) => {
          if (response.data.code == 906) {
            // return  alert('token已过期')
            this.$router.push(`/login`);
          }

          console.log("录入的行政区划", response);
          const userAreaCode = response.data.data.areacode;
          const yearMonth = this.queryForm.yearMonth; // 获取选择的年月
          console.log("年月", yearMonth);
          this.fetchData(userAreaCode, yearMonth); // 传递年月信息// 示例用户区域编码
          // this.fetchData(userAreaCode)
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    fetchData(userAreaCode, yearMonth) {
      // 调用 user.js 中的 getData 方法
      this.$api
        .getNDmSzjcInfo(userAreaCode, yearMonth)
        .then((response) => {
          console.log("拿到的数据", response);
          this.tableData = response.data.data;
          let data = response.data.data;
          data.forEach(element => {
            console.log(element.jianceshijian);
            element.btnstate = '0';
            if (element.jianceshijian == '月') {
              element.btnstate = '0';
            } else if (element.jianceshijian == '季度') {
              element.btnstate = '1';
              if (['03', '06', '09', '12'].includes(yearMonth.substring(5))) {
                element.btnstate = '2';
              }
            }
            console.log(element.btnstate);
          });
          this.totalItems = this.tableData.length;
          this.paginateData();
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },

    // 查询
    onSearch() {
      console.log("查询");
      const keyword = this.queryForm.keyword.trim().toLowerCase();
      console.log("遍历的数据", this.tableData);

      this.filteredData = this.tableData.filter((item) =>
        String(item.dmmc).toLowerCase().includes(keyword)
      );

      console.log(this.filteredData);

      this.paginatedData = this.filteredData;
      this.totalItems = this.filteredData.length;
    },

    // 修改
    // handleButtonClick(row) {
    //   // 处理按钮点击事件
    //   // 可以根据需要执行特定操作
    //   console.log("点击了操作按钮，当前行数据:", row);
    //   // 获取当前行的 ID
    //   // const id = row.sampleinfoid;
    //   const id = row.id;
    //   // const id = row.sampleid;
    //   console.log(1111, id);
    //   // 导航到编辑页面
    //   this.$router.push({ name: "EditPage", params: { id } });
    // },
    // 录入数据
    handleEntry(row) {
      // 根据需求处理录入操作，跳转或弹出录入页面等
      if (row.btnstate == '1') {
        return;
      }
      this.$router.push({
        name: "NewData",
        params: {...row, ...{ jcsj: this.queryForm.yearMonth }},
      });
    },
    // 修改数据
    handleEdit(row) {
      // 根据需求处理修改操作，跳转或弹出修改页面等
      console.log("修改操作", row);
      this.$router.push({
        name: "NewData",
        params: { dmmc: row.dmmc, id: row.dmszjcid, xzqhname: row.xzqhname,shenhezt: row.shenhezt},
      });
    },
    // 查看数据
    handleView(row) {
      // 根据需求处理查看操作，跳转或弹出详情页面等
      console.log("查看操作", row);
      this.dialogVisible = true;
      this.$api.getNDmSzjcDataById(row.dmszjcid).then((res) => {
        console.log(res);
        if (res.data.code == 0) {
          let data = res.data.data;
          data.xzqhname = row.xzqhname;
          data.liuyu = row.liuyu;
          data.szmb = row.szmb;
          data.dmlaiyuan = row.dmlaiyuan;
          data.szlbname = data.szlb != '0' ? config.typeArray.find(item => item.value == data.szlb).label : '';
          console.log(data);
          let filelist = data.filename ? data.filename.split('|').map(item => ({name: item, url: process.env.VUE_APP_URL_API + item})) : '';
          console.log(filelist);
          data.filelist = filelist;
          this.dmData = [data];
        }
      }).catch((error) => {
        console.log(error);
      })
      // this.$router.push({
      //   name: "NewData",
      //   query: { dmmc: row.dmmc, id: row.dmszjcid, shenhezt: row.shenhezt },
      // });
    },

    // 删除

    async deleteItem(id) {
      console.log("删除id", id);
      try {
        MessageBox.confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 用户点击了确定按钮
            console.log("用户点击了确定按钮");

            this.$api
              .deleteNDmSzjcData(id)
              .then((response) => {
                // 处理接口返回的数据或其他逻辑

                // 处理删除成功的情况
                console.log("删除成功", response.data);
                this.$message.success("删除成功");

                // 在前端移除已删除的项
                this.tableData = this.tableData.filter(
                  (item) => item.id !== id
                );
                this.totalItems--; // 减少总项目数
                this.paginateData(); // 更新分页后的数据
                this.getUser();
              })
              .catch((error) => {
                // 处理失败的情况
                console.error("失败:", error);
              });
          })
          .catch(() => {
            // 用户点击了取消按钮
            console.log("用户点击了取消按钮");
          });
      } catch (error) {
        // 处理删除失败的情况
        console.error("删除失败", error);
      }
    },
    // 切换分页
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = this.tableData.slice(start, end);
    },
    handleSelectionChange(selection) {
      console.log(selection);
      let data = selection.filter(item => item.shenhezt == '01' || item.shenhezt == '04');
      this.selectedIds = data.map((item) => item.dmszjcid);
    },
    handleCurrentChange(val) {
      // 当用户切换分页时触发
      this.currentPage = val;
      this.paginateData();
    },
    // 根据审核状态返回标签类型
    getTagType(shenhezt) {
      switch (shenhezt) {
        case "00":
          return "info"; // 未录入
        case "01":
          return "warning"; // 未提交
        case "02":
          return "primary"; // 等待盟市审核
        case "03":
          return "success"; // 审核通过
        case "04":
          return "danger"; // 审核未通过
        default:
          return "info"; // 默认为未录入
      }
    },
    // 根据审核状态返回对应的文本
    getStatusText(shenhezt) {
      console.log("状态", shenhezt);
      switch (shenhezt) {
        case "00":
          return "未录入";
        case "01":
          return "未提交";
        case "02":
          return "等待盟市审核";
        case "03":
          return "审核通过";
        case "04":
          return "审核未通过";
        default:
          return "未录入";
      }
    },
    // 一键提交
    confirmSubmit() {
      console.log(this.selectedIds);
      if (this.selectedIds.length == 0) {
        this.$message('请选择可提交的数据！');
        return;
      }
    // 弹出确认对话框
    this.$confirm(`已选择${this.selectedIds.length}条可提交数据，确定要提交吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }).then(() => {
      // 用户点击了确定按钮，调用提交接口
      this.$api
            .batshenheNDmSzjcData(this.selectedIds, '02') // 假设调用的接口名为 oneKeyAudit
            .then((response) => {
              // 处理一键审核成功的逻辑
              console.log("批量审核返回的数据", response);
              this.$message.success("一键提交成功");
              this.getUser(); // 刷新数据
            })
            .catch((error) => {
              // 处理一键审核失败的逻辑
              console.error("一键审核失败", error);
              this.$message.error("一键提交失败");
            });
    }).catch(() => {
      // 用户点击了取消按钮，不执行任何操作
    });
  },
  },
};
</script>

<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}
/* .box {
    padding: 15px;
    background: rgb(255, 255, 255);
    height: 700px;
    position: relative;
    overflow-y: auto;
  } */
.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}
.center {
  /* height: 400px; */
}
.el-form-item {
  margin-bottom: 2px;
  vertical-align: top;
  margin-right: 16px;
}
.bottom {
  text-align: right;
}

.file-upload {
  margin-right: 20px; /* 调整按钮之间的间距 */
}
.file-upload input {
  display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
  display: inline-block;
  cursor: pointer;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 5px;
}

.dialog-content {
  display: flex;
  /* flex-direction: column; */
  /* align-items: center; */
  justify-content: center;
  height: 100%;
}
.el-dialog__body {
  padding-top: 0;
}
</style>
